package org.rc.web;

import org.rc.model.Statistics;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

import org.rc.dao.GenericDao;
import org.rc.dao.RaceDao;
import org.rc.model.Athlete;
import org.rc.model.Race;
import org.rc.task.TaskManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Admin servlet. Handle requests for /admin
 * 
 */
public class AdminServlet extends IndexServlet {

    private static final Logger LOGGER = LoggerFactory.getLogger(AdminServlet.class);
    private GenericDao<Athlete> athleteDao = new GenericDao<Athlete>(Athlete.class);
    private GenericDao<Statistics> statsDao = new GenericDao<Statistics>(Statistics.class);
    private RaceDao raceDao = new RaceDao();
    private TaskManager taskManager = new TaskManager();


    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        handle(request, response);
    }

    private void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if(isDataTablesRequest(request)) {
            Integer startRow = new Integer(request.getParameter("iDisplayStart"));
            Integer sEcho = new Integer(request.getParameter("sEcho"));
            Integer pageSize = new Integer(request.getParameter("iDisplayLength")); //FIXME:catch exceptions here
            List<Race> races = raceDao.getPageOfRaces(startRow, pageSize);
            RaceTablePage rtp = new RaceTablePage(races);
            long totalRaces = statsDao.getAll().get(0).getNumberOfRaces();
            rtp.setiTotalRecords(""+totalRaces);
            rtp.setiTotalDisplayRecords("" + totalRaces);
            rtp.setsEcho(sEcho);
            response.setContentType("applicaiton/json");
            response.getWriter().write(rtp.asJson());

        } else if(request.getParameter("task")!=null) {
            String task = request.getParameter("task");
            taskManager.runTask(task, request.getParameterMap());
        } else {
            request.setAttribute("tasks", taskManager.getTasks().values());
            forward(request, response, "admin.jsp");
        }
    }

    /**
     * Process POST. Handle various "actions"
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException 
     */
    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        handle(request,response);
    }
}
